<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader :list="list" @add="addFn"></TodoHeader>
    <TodoMain :list="todoList"></TodoMain>
    <TodoFooter
      :farr="todoList"
      @changeType="typeFn"
      @clear="clearFn"
      :sel="sel"
      :len="len"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css";
import "./styles/index.css";

import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("todolist")) || [],
      sel: "all",
    };
  },
  methods: {
    addFn(val) {
      if (val.trim() === "") return alert("请填写完整");
      this.list.push({
        id: this.list.length ? this.list.at(-1).id + 1 : 100,
        name: val,
        isDone: false,
      });
    },
    typeFn(str) {
      console.log(str);
      // 'all' 'yes' 'no' // 修改类型
      this.sel = str;
    },
    clearFn() {
      this.list = this.list.filter((obj) => !obj.isDone);
    },
  },
  computed: {
    todoList() {
      if (this.sel === "yes") {
        // 显示已完成
        return this.list.filter((obj) => obj.isDone);
      } else if (this.sel === "no") {
        // 显示未完成
        return this.list.filter((obj) => !obj.isDone);
      } else {
        return this.list; // 全部显示
      }
    },
    len() {
      return this.todoList.length;
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("todolist", JSON.stringify(this.list));
      },
    },
  },
};
</script>